<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>defineProperty</title>
  </head>
  <body>
    <h2></h2>
    <button>更新dom</button>
    <script>
      const p = {
        name: "张三",
        age: 18,
      };

      let vm = {};
      for (let key in p) {
        Object.defineProperty(vm, key, {
          enumerable: true,
          configurable: true,
          get() {
            return p[key];
          },
          set(newVal) {
            if (newVal === p[key]) return;
            p[key] = newVal;
            nofify(newVal);
          },
        });
      }

      function nofify(newVal) {
        console.log("通知", newVal);
        document.querySelector("h2").innerHTML = newVal;
      }
      nofify("李四");
      document.querySelector("button").onclick = function () {
        vm.name = "王五";
      };
    </script>
  </body>
</html>
